package com.syg.rabbitmq.producer;


import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * Topic模式需要声明Topic交换机
 * <br/>
 * #表示一个或多个单词，*表示匹配一个单词(注意：点分割表示一个单词)
 * <br/>
 *
 * <img width="957px" height="455px" src="../../../../../resources/picture/topic模式.png" alt="Topic模式需要声明Topic交换机">
 *     <br/>
 *     和Routing模式唯一的不同就是可以设置带有通配符进行模糊匹配的rutingKey
 */
public class Topic_Producer {

    public static void main(String[] args) throws IOException, TimeoutException {

        // 1,创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();

        //2,设置参数
        factory.setHost("127.0.0.1");
        factory.setPort(5672);
        factory.setUsername("guest");
        factory.setPassword("guest");
        factory.setVirtualHost("/");

        // 3,创建连接
        Connection connection = factory.newConnection();
        // 4,创建Channel
        Channel channel = connection.createChannel();

        /*
         * exchangeDeclare(String exchange,BuiltinExchangeType type,boolean durable,boolean autoDelete,boolean internal,Map<String, Object> arguments)
         * 参数：
         *   exchange：交换机
         *   type：交换机类型
         *   durable:持久化
         *   autoDelete：自动删除
         *   internal：mq内部使用,一般false
         *   arguments：参数
         * */
        // 5,创建交换机(如果交换机名一样,类型不一样,则报错)
        String exchangeName = "test_topic";
        channel.exchangeDeclare(exchangeName, BuiltinExchangeType.TOPIC, true, false, false, null);

        // 6,创建队列
        String queueTopic1 = "queueTopic1";
        String queueTopic2 = "queueTopic2";
        channel.queueDeclare(queueTopic1, true, false, false, null);
        channel.queueDeclare(queueTopic2, true, false, false, null);


        // Topic模式,需要指定routingKey
        channel.queueBind(queueTopic1, exchangeName, "#.log");
        // 队列2的绑定
        channel.queueBind(queueTopic2, exchangeName, "error.*");
        channel.queueBind(queueTopic2, exchangeName, "*.log");
        channel.queueBind(queueTopic2, exchangeName, "*.*");

        // ------执行以上代码,管理台会看到队列与交换机-----------

        // 8,发送消息(点分割表示一个单词)
        String routingKey = "err.orhahahah.log";
        String content = "direct类型的交换机——Routing模式,需要指定routingKey=" + routingKey;
        channel.basicPublish(exchangeName, routingKey, null, content.getBytes());

        // 9,释放资源
    }
}
